package com.example.webdemo.util;

//Token生成组件，缺少依赖项，暂不确定是否继续安保组件开发

import com.example.webdemo.bean.user;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component // 添加组件注解
public class JwtTokenUtil { // 移除所有static修饰符

    private static String secret;
    private static int expiration;

    @Value("${jwt.secret}")
    public void setSecret(String sec) {
        secret = sec; // 通过Setter注入静态字段
    }

    @Value("${jwt.expiration}")
    public void setExpiration(int exp) {
        expiration = exp; // 通过Setter注入静态字段
    }

    // 改为实例方法
    public static String generateToken(user user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUser_id());
        return createToken(claims, user.getUsername());
    }

    // 改为实例方法
    private static String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000L))
                .signWith(SignatureAlgorithm.HS256, secret) // 使用注入的secret
                .compact();
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }
}
